from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal, QTimer
import os
import time
import platform

#https://stackoverflow.com/questions/36175717/importerror-no-module-named-pyqt5-qtquick
# 树莓派 PyQt5 的 qquick 缺失解决
# sudo apt-get install python3-pyqt5.qtquick


# 定义一个类，将我们需要用到的方法、变量等都放到里面，便于调用
class Network(QObject):

    # https://blog.csdn.net/qq_16792139/article/details/110677005
    netstateSig = pyqtSignal(bool, arguments=['connected']) # str,int 为信号传递的参数类型,  name,value 为QMl中使用它们时的名字

    def __init__(self):
        super().__init__()
        self.timer = QTimer(interval=4000, timeout=self.netCheck)

    @pyqtSlot()
    def tellQmlNetStatus(self, connected:bool):
        self.netstateSig.emit(connected)

    def netCheck(self):
        '''
        #windows ping limit times:  ping -n 1 www.baidu.com>nul
        #linux ping limit times: ping -c 1 www.baidu.com >/dev/null
        '''
        cmd = ''
        if platform.system() == 'Windows':
            cmd = 'ping -n 1 www.baidu.com>nul'
        else:
            cmd = 'ping -c 1 www.baidu.com >/dev/null'
        return1 = os.system(cmd)
        if return1:
            print('ping fail')
            self.tellQmlNetStatus(False)
        else:
            # print('ping Ok')
            self.tellQmlNetStatus(True)

    def startCheck(self):
        self.timer.start()

    def stopCheck(self):
        self.timer.stop()
        print(1)